package com.le.buddha.websocket;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dashscope.app.ApplicationResult;
import com.le.buddha.conf.ThreadPoolConfig;
import com.le.buddha.mobile.User;
import com.le.buddha.mobile.VoiceModel;
import com.le.buddha.mobile.enums.SysConfigEnum;
import com.le.buddha.service.*;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 收到客户端消息逻辑处理
 * @author guole
 * @created 2025/1/12
 */
@Service
@Slf4j
public class MessageHandle  {

    @Resource
    private IVoiceService voiceService;
    @Resource
    private ThreadPoolConfig threadPoolConfig;
    @Resource
    private ALiGptService aLiGptService;
    @Resource
    private IFileService fileService;
    @Resource
    private IChatHistoryService chatHistoryService;
    @Resource
    private IUserService userService;

    @Value("${fileServer}")
    private String fileUrl;

    @Resource
    private IVoiceModeService voiceModeService;
    @Resource
    private ISysConfigService sysConfigService;
    public void handle(String oid, String requestTxt) {


        User user = userService.queryUserByToken(oid);
        String sessionId = chatHistoryService.queryChatHistorySessionId(user.getId());
        try {
            Flowable<ApplicationResult> flowable = aLiGptService.send(requestTxt, sessionId);
            String answer = sendMessage(oid, flowable);
            chatHistoryService.saveChatHistory(user.getId(), requestTxt, answer, sessionId);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String sendMessage(String oid, Flowable<ApplicationResult> flowable) {
        StringBuilder resultBuilder = new StringBuilder();
        StringBuilder musicMessageBuilder = new StringBuilder();
        List<String> musicTextList = new ArrayList<>();


        AtomicBoolean isStop = new AtomicBoolean(false);
        //处理语音消息
        sendMusic(oid, musicTextList, isStop);
        //处理文本消息
        try {
            flowable.blockingForEach(data -> {
                String outTxt = data.getOutput().getText();
                String outMusicTxt = "";
                if (!data.getOutput().getFinishReason().equals("stop")) {
                    resultBuilder.append(outTxt);
                    musicMessageBuilder.append(outTxt);
                    if (outTxt.contains("。")) {

                        String strs[] = musicMessageBuilder.toString().split("。");
                        //获取句号前面的内容
                        outMusicTxt =  strs[0] + "。";
                        //获取句号后面的内容
                        musicMessageBuilder.setLength(0);
                        musicMessageBuilder.append(strs.length > 1 ? strs[1] : "");
                    }
                } else {
                    outTxt = "stop";
                    if (musicMessageBuilder.length() > 0) {
                        outMusicTxt = musicMessageBuilder.toString();

                    }
                }
                WebSocketSever.sendMessageByUser(oid, outTxt, 1);
                if (StrUtil.isNotEmpty(outMusicTxt)) {
                    musicTextList.add(outMusicTxt);
                    outMusicTxt = "";
                }
                if (outTxt.equals("stop")) {
                    isStop.set(true);
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultBuilder.toString();
    }

    private void sendMusic(String oid, List<String> musicTextList, AtomicBoolean isStop) {
        threadPoolConfig.threadPoolTaskExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Long voiceId=Long.parseLong( sysConfigService.queryValueByCode(SysConfigEnum.声音模型ID.getCode()))   ;
                    VoiceModel voiceModel=voiceModeService.lambdaQuery().eq(VoiceModel::getId,voiceId).one();
                    String modelName=voiceModel.getModelName();
                    Integer speech=voiceModel.getSpeech();
                    while (true) {


                        if (musicTextList.size() == 0 && isStop.get()) {
                            break;
                        }
                        if (musicTextList.size() == 0) {
                            continue;
                        }
                        String message = musicTextList.remove(0);

                        byte[] music = voiceService.textToSpeech(message, modelName,speech);
                        String path = fileUrl + fileService.upload(music, "mp3", 2);
                        //发送语音
                        WebSocketSever.sendMessageByUser(oid, path, 2);

                    }
                } catch (Exception e) {
                   e.printStackTrace();
                }

            }
        });
    }


}
